package com.reds.backend.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.reds.backend.common.ApiResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 全局异常拦截
    // 拦截：未登录异常
    @ExceptionHandler(NotLoginException.class)
    public ApiResponse<Void> handlerException(NotLoginException e) {
        // 打印堆栈，以供调试
        e.printStackTrace();
        // 返回给前端
        return ApiResponse.failure(401, e.getMessage());
    }

    // 拦截：缺少权限异常
    @ExceptionHandler(NotPermissionException.class)
    public ApiResponse<Void> handlerException(NotPermissionException e) {
        e.printStackTrace();
        return ApiResponse.failure(403, "缺少权限：" + e.getPermission());
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    public ApiResponse<Void> handlerException(NotRoleException e) {
        e.printStackTrace();
        return ApiResponse.failure(403, "缺少角色：" + e.getRole());
    }



    // 拦截：其它所有异常
    @ExceptionHandler(Exception.class)
    public ApiResponse<Void> handlerException(Exception e) {
        e.printStackTrace();
        return ApiResponse.failure(500, e.getMessage());
    }
}
